#include "usersettingswidget.h"
#include "errorhandler.h"
#include <QApplication>
#include <QStyle>
#include <QDir>
#include <QStandardPaths>

UserSettingsWidget::UserSettingsWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_notificationGroup(nullptr)
    , m_notificationLayout(nullptr)
    , m_enableNotificationsCheck(nullptr)

    , m_dataGroup(nullptr)
    , m_dataLayout(nullptr)
    , m_clearCacheButton(nullptr)
    , m_clearHistoryButton(nullptr)
    , m_cacheInfoLabel(nullptr)
    , m_actionGroup(nullptr)
    , m_actionLayout(nullptr)
    , m_saveButton(nullptr)
    , m_resetButton(nullptr)
    , m_statusLabel(nullptr)
    , m_dataManager(nullptr)
    , m_isInitialized(false)
    , m_isLoading(false)
{
    // 获取DataManager实例
    m_dataManager = &DataManager::instance();
    
    // 初始化界面
    initializeUI();
    
    m_isInitialized = true;
}

UserSettingsWidget::~UserSettingsWidget()
{
    // Qt会自动清理子对象
}

void UserSettingsWidget::setUserId(const QString& userId)
{
    m_currentUserId = userId;
    
    if (!userId.isEmpty()) {
        loadUserSettings();
    } else {
        // 清空设置
        m_currentSettings = UserSettings();
        m_originalSettings = UserSettings();
        applySettingsToUI(m_currentSettings);
    }
    
    updateUIState();
}

void UserSettingsWidget::loadUserSettings()
{
    if (m_currentUserId.isEmpty()) {
        return;
    }
    
    m_isLoading = true;
    
    // 从数据管理器加载用户设置
    // 注意：这里假设DataManager有getUserSettings方法，如果没有则使用默认设置
    m_currentSettings = UserSettings(m_currentUserId);
    m_originalSettings = m_currentSettings;
    
    // 应用设置到界面
    applySettingsToUI(m_currentSettings);
    
    // 更新缓存信息
    updateCacheInfo();
    
    m_isLoading = false;
    updateUIState();
}

void UserSettingsWidget::saveUserSettings()
{
    if (m_currentUserId.isEmpty()) {
        showOperationResult("请先选择用户", false);
        return;
    }
    
    // 获取当前界面设置
    UserSettings settings = getCurrentSettings();
    
    // 验证设置
    if (!settings.isValid()) {
        showOperationResult(QString("设置验证失败: %1").arg(settings.getValidationError()), false);
        return;
    }
    
    // 保存设置（这里简化处理，实际应该通过DataManager保存）
    m_currentSettings = settings;
    m_originalSettings = settings;
    
    // 发射设置更新信号
    emit settingsUpdated(m_currentUserId, settings);
    
    showOperationResult("设置已保存");
    updateUIState();
}

void UserSettingsWidget::resetToDefaults()
{
    UserSettings defaultSettings(m_currentUserId);
    applySettingsToUI(defaultSettings);
    showOperationResult("已重置为默认设置");
}

void UserSettingsWidget::onSettingsSaved()
{
    showOperationResult("设置保存成功");
}

void UserSettingsWidget::onOperationError(const QString& errorMessage)
{
    showOperationResult(errorMessage, false);
}

void UserSettingsWidget::onSaveButtonClicked()
{
    saveUserSettings();
}

void UserSettingsWidget::onResetButtonClicked()
{
    if (hasUnsavedChanges()) {
        int ret = QMessageBox::question(this, "确认重置", 
                                       "确定要重置为默认设置吗？未保存的更改将丢失。",
                                       QMessageBox::Yes | QMessageBox::No,
                                       QMessageBox::No);
        if (ret != QMessageBox::Yes) {
            return;
        }
    }
    
    resetToDefaults();
}

void UserSettingsWidget::onClearCacheClicked()
{
    int ret = QMessageBox::question(this, "清除缓存", 
                                   "确定要清除应用缓存吗？这将删除临时文件和缓存数据。",
                                   QMessageBox::Yes | QMessageBox::No,
                                   QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        // 清除缓存逻辑
        try {
            // 这里可以添加清除缓存的具体实现
            // 例如删除临时文件、清理内存缓存等
            
            showOperationResult("缓存已清除");
            updateCacheInfo();
        } catch (const std::exception& e) {
            showOperationResult(QString("清除缓存失败: %1").arg(e.what()), false);
        }
    }
}

void UserSettingsWidget::onClearHistoryClicked()
{
    int ret = QMessageBox::question(this, "清除历史", 
                                   "确定要清除用户历史数据吗？这将删除订单历史等信息，此操作不可恢复。",
                                   QMessageBox::Yes | QMessageBox::No,
                                   QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        // 再次确认
        ret = QMessageBox::warning(this, "最终确认", 
                                  "警告：此操作将永久删除历史数据，确定继续吗？",
                                  QMessageBox::Yes | QMessageBox::No,
                                  QMessageBox::No);
        
        if (ret == QMessageBox::Yes) {
            // 发射数据清理请求信号
            emit dataClearRequested();
            showOperationResult("历史数据清除请求已发送");
        }
    }
}

void UserSettingsWidget::onSettingsChanged()
{
    if (m_isLoading || !m_isInitialized) {
        return;
    }
    
    updateUIState();
}

void UserSettingsWidget::initializeUI()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(20, 20, 20, 20);
    m_mainLayout->setSpacing(15);
    
    // 创建各个区域
    createNotificationArea();
    createDataManagementArea();
    createActionArea();
    
    // 创建状态标签
    m_statusLabel = new QLabel(this);
    m_statusLabel->setAlignment(Qt::AlignCenter);
    m_statusLabel->setVisible(false);
    m_mainLayout->addWidget(m_statusLabel);
    
    // 添加弹性空间
    m_mainLayout->addStretch();
    
    // 应用样式
    applyStyleSheet();
    
    // 初始状态
    updateUIState();
}

void UserSettingsWidget::createNotificationArea()
{
    m_notificationGroup = new QGroupBox("通知设置", this);
    m_notificationLayout = new QVBoxLayout(m_notificationGroup);
    m_notificationLayout->setSpacing(10);
    
    // 启用通知复选框
    m_enableNotificationsCheck = new QCheckBox("启用系统通知", this);
    m_enableNotificationsCheck->setChecked(true);
    m_enableNotificationsCheck->setToolTip("开启后将在订单状态变化时显示系统通知");
    connect(m_enableNotificationsCheck, &QCheckBox::toggled, this, &UserSettingsWidget::onSettingsChanged);
    m_notificationLayout->addWidget(m_enableNotificationsCheck);
    
    // 添加说明文本
    QLabel* notificationDesc = new QLabel("系统通知将在订单状态更新时提醒您", this);
    notificationDesc->setStyleSheet("color: #666; font-size: 11px;");
    notificationDesc->setWordWrap(true);
    m_notificationLayout->addWidget(notificationDesc);
    
    m_mainLayout->addWidget(m_notificationGroup);
}



void UserSettingsWidget::createDataManagementArea()
{
    m_dataGroup = new QGroupBox("数据管理", this);
    m_dataLayout = new QVBoxLayout(m_dataGroup);
    m_dataLayout->setSpacing(10);
    
    // 缓存信息标签
    m_cacheInfoLabel = new QLabel("缓存信息加载中...", this);
    m_cacheInfoLabel->setStyleSheet("color: #666; font-size: 11px;");
    m_dataLayout->addWidget(m_cacheInfoLabel);
    
    // 按钮容器
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(10);
    
    // 清除缓存按钮
    m_clearCacheButton = new QPushButton("清除缓存", this);
    m_clearCacheButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogResetButton));
    m_clearCacheButton->setToolTip("清除应用缓存文件");
    connect(m_clearCacheButton, &QPushButton::clicked, this, &UserSettingsWidget::onClearCacheClicked);
    buttonLayout->addWidget(m_clearCacheButton);
    
    // 清除历史按钮
    m_clearHistoryButton = new QPushButton("清除历史", this);
    m_clearHistoryButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_TrashIcon));
    m_clearHistoryButton->setToolTip("清除用户历史数据（不可恢复）");
    connect(m_clearHistoryButton, &QPushButton::clicked, this, &UserSettingsWidget::onClearHistoryClicked);
    buttonLayout->addWidget(m_clearHistoryButton);
    
    // 添加弹性空间
    buttonLayout->addStretch();
    
    m_dataLayout->addLayout(buttonLayout);
    
    m_mainLayout->addWidget(m_dataGroup);
}

void UserSettingsWidget::createActionArea()
{
    m_actionGroup = new QGroupBox("操作", this);
    m_actionLayout = new QHBoxLayout(m_actionGroup);
    m_actionLayout->setSpacing(10);
    
    // 保存按钮
    m_saveButton = new QPushButton("保存设置", this);
    m_saveButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogApplyButton));
    connect(m_saveButton, &QPushButton::clicked, this, &UserSettingsWidget::onSaveButtonClicked);
    m_actionLayout->addWidget(m_saveButton);
    
    // 重置按钮
    m_resetButton = new QPushButton("重置默认", this);
    m_resetButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogResetButton));
    connect(m_resetButton, &QPushButton::clicked, this, &UserSettingsWidget::onResetButtonClicked);
    m_actionLayout->addWidget(m_resetButton);
    
    // 添加弹性空间
    m_actionLayout->addStretch();
    
    m_mainLayout->addWidget(m_actionGroup);
}

void UserSettingsWidget::applyStyleSheet()
{
    // 为1024*600分辨率优化的样式
    setStyleSheet(R"(
        QGroupBox {
            font-size: 13px;
            font-weight: bold;
            color: #333;
            border: 2px solid #ddd;
            border-radius: 6px;
            margin-top: 8px;
            padding-top: 8px;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 12px;
            padding: 0 6px 0 6px;
            background-color: white;
        }
        
        QCheckBox {
            font-size: 12px;
            color: #333;
            spacing: 8px;
        }
        
        QCheckBox::indicator {
            width: 16px;
            height: 16px;
        }
        
        QCheckBox::indicator:unchecked {
            border: 2px solid #ddd;
            border-radius: 3px;
            background-color: white;
        }
        
        QCheckBox::indicator:checked {
            border: 2px solid #4CAF50;
            border-radius: 3px;
            background-color: #4CAF50;
            image: url();
        }
        
        QPushButton {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            min-width: 80px;
        }
        
        QPushButton:hover {
            background-color: #2980B9;
        }
        
        QPushButton:pressed {
            background-color: #21618C;
        }
        
        #saveButton {
            background-color: #4CAF50;
            color: white;
        }
        
        #saveButton:hover {
            background-color: #45a049;
        }
        
        #resetButton {
            background-color: #FF9800;
            color: white;
        }
        
        #resetButton:hover {
            background-color: #F57C00;
        }
        
        #clearCacheButton {
            background-color: #2196F3;
            color: white;
        }
        
        #clearCacheButton:hover {
            background-color: #1976D2;
        }
        
        #clearHistoryButton {
            background-color: #f44336;
            color: white;
        }
        
        #clearHistoryButton:hover {
            background-color: #d32f2f;
        }
        
        QLabel {
            font-size: 12px;
            color: #333;
        }
        
        .status-success {
            color: #4CAF50;
            font-weight: bold;
            background-color: #E8F5E8;
            padding: 6px;
            border-radius: 4px;
            border: 1px solid #4CAF50;
        }
        
        .status-error {
            color: #f44336;
            font-weight: bold;
            background-color: #FFEBEE;
            padding: 6px;
            border-radius: 4px;
            border: 1px solid #f44336;
        }
    )");
    
    // 设置按钮ID以应用特定样式
    m_saveButton->setObjectName("saveButton");
    m_resetButton->setObjectName("resetButton");
    m_clearCacheButton->setObjectName("clearCacheButton");
    m_clearHistoryButton->setObjectName("clearHistoryButton");
}

void UserSettingsWidget::updateUIState()
{
    bool hasValidUser = !m_currentUserId.isEmpty();
    bool hasChanges = hasUnsavedChanges();
    
    // 启用/禁用控件
    m_notificationGroup->setEnabled(hasValidUser);

    m_dataGroup->setEnabled(hasValidUser);
    m_saveButton->setEnabled(hasValidUser && hasChanges);
    m_resetButton->setEnabled(hasValidUser);
    
    if (!hasValidUser) {
        m_statusLabel->setText("请先选择用户");
        m_statusLabel->setProperty("class", "status-error");
        m_statusLabel->setVisible(true);
    } else if (!m_isLoading && !m_statusLabel->isVisible()) {
        // 只在没有其他状态显示时隐藏
        m_statusLabel->setVisible(false);
    }
}

void UserSettingsWidget::showOperationResult(const QString& message, bool success)
{
    m_statusLabel->setText(message);
    m_statusLabel->setProperty("class", success ? "status-success" : "status-error");
    m_statusLabel->style()->polish(m_statusLabel); // 重新应用样式
    m_statusLabel->setVisible(true);
    
    // 3秒后隐藏状态标签
    QTimer::singleShot(STATUS_DISPLAY_MS, [this]() {
        if (m_statusLabel) {
            m_statusLabel->setVisible(false);
            updateUIState(); // 重新更新状态
        }
    });
}

UserSettings UserSettingsWidget::getCurrentSettings() const
{
    UserSettings settings(m_currentUserId);
    settings.enableNotifications = m_enableNotificationsCheck->isChecked();

    settings.lastModified = QDateTime::currentDateTime();
    return settings;
}

void UserSettingsWidget::applySettingsToUI(const UserSettings& settings)
{
    m_isLoading = true;
    
    m_enableNotificationsCheck->setChecked(settings.enableNotifications);

    
    m_isLoading = false;
}

bool UserSettingsWidget::hasUnsavedChanges() const
{
    if (m_currentUserId.isEmpty() || m_isLoading) {
        return false;
    }
    
    UserSettings current = getCurrentSettings();
    
    return (current.enableNotifications != m_originalSettings.enableNotifications ||
            current.autoLogin != m_originalSettings.autoLogin);
}

void UserSettingsWidget::updateCacheInfo()
{
    // 简化的缓存信息显示
    QString cacheInfo = "应用运行正常，缓存状态良好";
    
    // 这里可以添加实际的缓存大小计算逻辑
    // 例如检查临时文件夹大小等
    
    m_cacheInfoLabel->setText(cacheInfo);
}
